/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.dark.common.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.dark.common.utils.LogUtils;
import com.dark.common.web.model.ExceptionResponse;
import com.dark.common.web.utils.DateEditor;

/**
 * 基础控制器
 * <p>User: 杨浩泉
 * <p>Date: 2015-4-22
 * <p>Version: 1.0
 */
public abstract class BaseController {

    private String viewPrefix;


    protected BaseController() {
        setViewPrefix(defaultViewPrefix());
    }
    
    @InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		/**
		 * 自动转换日期类型的字段格式
		 */
		binder.registerCustomEditor(Date.class, new DateEditor());
	}


    /**
     * 设置通用数据
     *
     * @param model
     */
    protected void setCommonData(Model model) {
    }


    /**
     * 当前模块 视图的前缀
     * 默认
     * 1、获取当前类头上的@RequestMapping中的value作为前缀
     * 2、如果没有就使用当前模型小写的简单类名
     */
    public void setViewPrefix(String viewPrefix) {
        if (viewPrefix.startsWith("/")) {
            viewPrefix = viewPrefix.substring(1);
        }
        this.viewPrefix = viewPrefix;
    }

    public String getViewPrefix() {
        return viewPrefix;
    }

    /**
     * 获取视图名称：即prefixViewName + "/" + suffixName
     *
     * @return
     */
    public String viewName(String suffixName) {
        if (!suffixName.startsWith("/")) {
            suffixName = "/" + suffixName;
        }
        return getViewPrefix() + suffixName;
    }

    /**
     * @param backURL null 将重定向到默认getViewPrefix()
     * @return
     */
    protected String redirectToUrl(String backURL) {
        if (StringUtils.isEmpty(backURL)) {
            backURL = getViewPrefix();
        }
        if (!backURL.startsWith("/") && !backURL.startsWith("http")) {
            backURL = "/" + backURL;
        }
        return "redirect:" + backURL;
    }

    protected String defaultViewPrefix() {
        String currentViewPrefix = "";
        RequestMapping requestMapping = AnnotationUtils.findAnnotation(getClass(), RequestMapping.class);
        if (requestMapping != null && requestMapping.value().length > 0) {
            currentViewPrefix = requestMapping.value()[0];
        }
        return currentViewPrefix;
    }
    
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e, HttpServletRequest request){
    	
    	if(e instanceof UnauthorizedException){
    		LogUtils.logError("用户权限验证失败", e);
    		ExceptionResponse exceptionResponse = ExceptionResponse.from(e);
    		
    		ModelAndView mv = new ModelAndView();
    		mv.addObject("error", exceptionResponse);
    		mv.setViewName("error/403");	
    		
    		return mv;
    	} else {
    		LogUtils.logError("运行时异常", e);
    		ExceptionResponse exceptionResponse = ExceptionResponse.from(e);
    		
    		ModelAndView mv = new ModelAndView();
    		mv.addObject("error", exceptionResponse);
    		mv.setViewName("error/exception"); 
    		
    		return mv;
    	}
    }
}
